package edu.mju.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.mju.security.entity.SecurityUser;
import edu.mju.security.entity.Users;
import edu.mju.security.utils.TokenUtils;
import edu.mju.servicebasic.exception.TravelException;
import edu.mju.serviceutils.ResponseCode;
import edu.mju.serviceutils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 自定义认证过滤器
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    private TokenUtils tokenUtils;

    private RedisTemplate redisTemplate;

    /**
     * 管理工具类
     */
    private AuthenticationManager authenticationManager;

    public LoginFilter(TokenUtils tokenUtils, RedisTemplate redisTemplate, AuthenticationManager authenticationManager) {
        this.tokenUtils = tokenUtils;
        this.redisTemplate = redisTemplate;
        this.authenticationManager = authenticationManager;
        //不止使用post提交
        this.setPostOnly(false);
        //设置登录路径，匹配POST提交
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/user/login","POST"));
    }

    /**
     * 重写attemptAuthentication方法，获取表单提交的用户名密码
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //获取表单提交数据
        try {
            Users users = new ObjectMapper().readValue(request.getInputStream(), Users.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(users.getUsername(), users.getPassword(),new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new TravelException(40000,"获取表单数据异常！");
        }

    }

    /**
     * 认证成功调用的方法
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //认证成功后，取得用户信息
        SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
        //生成token
        String token = tokenUtils.createToken(securityUser.getUsers().getUsername());
        //用户信息与权限列表 放入redis
        redisTemplate.opsForValue().set(securityUser.getUsers().getUsername(),securityUser.getPermissionList());
        //返回token
        ResponseUtil.out(response, ResponseCode.success().data("token",token));
    }

    /**
     * 认证失败调用的方法
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        super.unsuccessfulAuthentication(request, response, failed);
        ResponseUtil.out(response,ResponseCode.error().message("认证失败！"));
    }
}
